package com.adminkk.tools;

import javassist.*;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;

import java.lang.reflect.Method;


public final class ParameterNameUtils {


    public final static String[] getParameterNamesByJavassist(final Class<?> clazz, final Method method) {

        ClassPool pool = ClassPool.getDefault();
        try {
            CtClass ctClass = pool.get(clazz.getName());
            CtMethod ctMethod = ctClass.getDeclaredMethod(method.getName());

            // 使用javassist的反射方法的参数名
            MethodInfo methodInfo = ctMethod.getMethodInfo();
            CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
            LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute
                    .getAttribute(LocalVariableAttribute.tag);
            if (attr != null) {

                String[] rtv = new String[ctMethod.getParameterTypes().length];
                int len = ctMethod.getParameterTypes().length;
                // 非静态的成员函数的第一个参数是this
                int pos = Modifier.isStatic(ctMethod.getModifiers()) ? 0 : 1;
                for (int i = 0; i < len; i++) {
                    rtv[i] = attr.variableName(i + pos);
                }
                return rtv;
            }
        } catch (NotFoundException e) {
            System.out.println("获取异常"+ e.getMessage());
        }
        return new String[0];
    }



}
